<template>
<div class="app-container calendar-list-container">
    <div class="filter-container">
      <span style="margin-left:42px">输入地址：</span> 
      <el-input clearable  ref='search'  v-model="addQuery.address" style="width: 360px;margin-right:15px;" class="filter-item" placeholder="请输入地址" >
      </el-input>    
      <el-button class="filter-item" type="primary" v-waves  @click="showLocation" icon="el-icon-search">查找</el-button>
    </div>
    <div id="map_canvas" ref='map' style="width: 100%; height: 600px;margin-bottom:20px"></div>
    <el-form  :model="addQuery"  ref="addForm" label-position="right" label-width="120px" >
        <h6>注：地址、营业时间、图片不选择将会使用以前的数据</h6>
        <el-form-item label="所在国家">
          <el-radio-group  v-model="country">
            <el-radio :label="1">中国</el-radio>
            <el-radio :label="2">澳大利亚</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="使用范围" prop="agentArea">
          <!-- 添加key 让组件重新渲染 -->
          <pcq
            :key="country"
            :level='2'
            label='NAME'
            :proviceId='addQuery.province'
            :cityId='addQuery.city'
            :address='address'
            @change='onAddressChange'
          ></pcq>
        </el-form-item>   
        <el-form-item label="营业开始时间" prop="startTime">
            <el-time-picker
                v-model="addQuery.startTime"
                value-format="timestamp"
                placeholder="开始时间">
            </el-time-picker>
        </el-form-item>
        <el-form-item label="营业结束时间" prop="endTime">
            <el-time-picker
                v-model="addQuery.endTime"
                value-format="timestamp"
                placeholder="结束时间">
            </el-time-picker>
        </el-form-item>
        <el-form-item label="店铺图片" prop="businessTop">
            <el-upload
                action=""
                class="upload-demo"
                :http-request="fileUploads"
                :file-list="fileList"
                :limit="1"
                list-type="picture">
                <el-button size="small" type="primary">点击上传</el-button>
                <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
            </el-upload>
        </el-form-item>
        <el-form-item label="商家品类" prop="sortId">
            <el-select v-model="addQuery.sortId" placeholder="请选择商家品类">
                <el-option v-for="item in list" :label="item.sortName" :value="item.id" :key="item.id"></el-option>
            </el-select>
        </el-form-item>
        <el-form-item label="商户名称" prop="businessName">
          <el-input v-model="addQuery.businessName"  placeholder="请输入商户名称"></el-input>
        </el-form-item>
         <el-form-item label="商户号码" prop="businessPhone">
          <el-input v-model="addQuery.businessPhone"  placeholder="请输入商户号码"></el-input>
        </el-form-item>
        <el-form-item label="详细地址" prop="address">
          <el-input v-model="addQuery.address" placeholder="请输入详细地址"></el-input>
        </el-form-item>
      </el-form>
      <el-button type="primary" style="margin-left:40px;margin-bottom:40px" :loading="loading.add" @click="add">确定</el-button>
    
</div>
    
</template>

<script>
import pcq from '@/components/Address'
import { address } from '@/utils/getAddress'
import { Aus } from '@/utils/Australlia'
import { fileUpload } from '@/api/system'
import { addBusiness } from '@/api/agent'
import { getSort, getBusinessInfo, updateBusiness } from '@/api/agent'
import { validatePhone } from '@/utils/validate'
export default {
    name: 'join_detail',
    components: {
        pcq
    },
    computed:{
        address () {
            if (this.country === 1) {
                return address
            }
            let temp = Aus.map(item => {
                return {
                ...item,
                AREA_ID: item.id,
                NAME: item.name,
                FID: item.fid
                }
            })
            return temp
        }
    },
    watch: {
        addQuery: {
            deep: true,
            handler (nv, ov) {
                let { province, city } = nv
                if (province && city) {
                    this.addQuery.agentArea = province + city
                }
            }
        }
    },
    data() {
        var validatePass = (rule, value, callback) => {
        if (!validatePhone(value)) {
            return callback(new Error('请填写正确的手机号码'));
        } else {
            callback();
        }
        };
        return {
            country: 2,
            addRules:{
                agentArea: [{ required: true, message: '请选择店铺所在地址', trigger: 'blur' },],
                businessName: [{ required: true, message: '请输入店铺名称', trigger: 'blur' },],
                address: [{ required: true, message: '请输入详细地址', trigger: 'blur' },],
                startTime: [{ required: true, message: '请选择营业开始时间', trigger: 'blur' },],
                endTime: [{ required: true, message: '请选择营业结束时间', trigger: 'blur' },],
                businessTop: [{ required: true, message: '请上传门店图片', trigger: 'blur' },],
                sortId: [{ required: true, message: '请选择商家品类', trigger: 'change' },],
            },
            addQuery: {
                businessName: '',
                address: '',
                sortId: '',
                province: '',
                city: '',
                area: '',
                longitude: '',
                latitude: '',
                businessPhone: '',
                startTime: '',
                endTime: '',
                businessTop: '',
                agentArea: ''
            },
            rules: {},
            provices: '',
            loading: {
                add: false
            },
            dialog: {
                add: false
            },
            map: null,
            geocoder: null,
            place: '',
            list: [],
            tempQuery: null,
            fileList: []
            
        }
    },
    methods: {
        formatDate (date) {
            const d = new Date(date)
            let h = d.getHours()
            let m = d.getMinutes()
            let s = d.getSeconds()
            h = h >= 10 ? h : '0' + h
            m = m >= 10 ? m : '0' + m
            s = s >= 10 ? s : '0' + s
            return `1970-08-08 ${h}:${m}:${s}`
        },
        onAddressChange (args) {
            let [province, city] = args
            this.addQuery.province = province
            this.addQuery.city = city
        },
        //获取分类列表
        async getHospitalList() {
            const { data } = await getSort({
                pageNo: 1,
                pageSize: 200,
            })
            this.list = data.records
            this.total = data.total
        },
        add() {
             this.$refs.addForm.validate(async valid => {
                if (valid) {
                    this.loading.add = true
                    console.log(this.addQuery.startTime);
                    this.addQuery.startTime = this.formatDate(this.addQuery.startTime)
                    this.addQuery.endTime = this.formatDate(this.addQuery.endTime)
                    let { ctime, ...query } = this.addQuery
                 
                    // let [startTime, endTime] = date
                    query = Object.assign({},  query)
                    for (const key in query) {
                        if (!query[key]) {
                            query[key] = this.tempQuery[key]
                        }
                    }
                    try {
                        const res = await updateBusiness(query)
                        if (res.code == 1) {
                            this.$message.success('操作成功')
                            setTimeout(() => {
                                this.$router.go(-1)
                            }, 1200);
                        }
                    } catch (error) {
                        console.log(error);
                        this.loading.add = false
                    }
                    this.loading.add = false
                } else {
                        console.log('error submit!!')
                        return false
                    }
            })
        },
        //上传图片
        async fileUploads({file}) {
            try{
                const fd = new FormData()
                fd.append('file', file)
                fd.append('fileName', 'indexPic')
                const res = await fileUpload(fd)
                this.addQuery.businessTop = res.data
            }catch(error) {

            }
        },
        initMap (latitude, longitude) {
            if (GBrowserIsCompatible()) {
                let options = {size:new GSize(1200, 700),mapTypes:[G_SATELLITE_MAP,G_NORMAL_MAP,G_PHYSICAL_MAP]};
                //map = new GMap2(document.getElementById("map_canvas"),{ size: new GSize(1200,700), mapTypes:[G_SATELLITE_MAP,G_NORMAL_MAP,G_PHYSICAL_MAP]} );
                this.map = new GMap2(document.getElementById("map_canvas"), options);
                this.map.disableGoogleBar();//禁用谷歌搜索栏
                this.map.setCenter(new GLatLng(latitude, longitude), 16);//设置坐标和放大倍数
                //这里点击显示地址
                this.map.addControl(new GSmallMapControl());
                GEvent.addListener(this.map, "click", this.getAddress);
                this.geocoder = new GClientGeocoder();
                let customUI = this.map.getDefaultUI();
                customUI.maptypes.hybrid = true;
                this.map.setUI(customUI);
                let point = new GLatLng(latitude, longitude);
                let marker = new GMarker(point);
                this.map.addOverlay(marker);
                marker.openInfoWindowHtml(`<div>${this.addQuery.address}</div>`);
            }
        },
        getAddress (overlay, latlng) {
            if (latlng != null) {
                this.geocoder.getLocations(latlng, this.showAddress);
            }
        },
        showAddress (response) {
            this.map.clearOverlays();
            if (!response || response.Status.code != 200) {
                this.$message.warn("你点击的这个地方还没有准确地址!"+"状态码（Status Code）:" + response.Status.code);
            } else {
                //alert(response.responseText); 
                let place = response.Placemark[0];
                let point = new GLatLng(place.Point.coordinates[1],
                    place.Point.coordinates[0]);
                let marker = new GMarker(point);
                this.map.addOverlay(marker);
                this.addQuery.address = place.address
                this.addQuery.longitude = place.Point.coordinates[0]
                this.addQuery.latitude = place.Point.coordinates[1] 
                marker.openInfoWindowHtml(
                '<div style="font-size:13px;">' +
                '<b>当前点击的地址:</b><br/>' + place.address + '<br/>' +
                '<b>坐标：</b>' + place.Point.coordinates[1] + '' + place.Point.coordinates[0]+'<br/>' +
                '<b>准确度:</b>' + place.AddressDetails.Accuracy + '&nbsp;&nbsp;&nbsp;&nbsp;' +
                '<b>国家代码:</b> ' + place.AddressDetails.Country.CountryNameCode) +       
                '</div>';
            }
        },
        showLocation () {
            if (!this.addQuery.address) {
                return
            }
            this.geocoder.getLocations(this.addQuery.address, this.addAddressToMap);
        },
        addAddressToMap (response) {
            this.map.clearOverlays();
            if (!response || response.Status.code != 200) {
                this.$message.error("不能解析这个地址");
            } else {
            let place = response.Placemark[0];
            let point = new GLatLng(place.Point.coordinates[1],
            place.Point.coordinates[0]);
            let marker = new GMarker(point);
            this.map.addOverlay(marker);
            marker.openInfoWindowHtml(this.getGeocodeHtml(response));
            }
        },
        getGeocodeHtml (response) {
            let html = "<div style='font-size:13px'>";
            html += "<b>搜索目标：</b>"+ response.name;
            if(response.Placemark){
                this.addQuery.longitude = response.Placemark[0].Point.coordinates[0]
                this.addQuery.latitude = response.Placemark[0].Point.coordinates[1]
                for (let i = 0, place; place = response.Placemark[i]; i++) {
                    html += "<br/><b>地址：</b>"+place.address;
                    if(place.AddressDetails.Country)html += "<br/><b>国家代码：</b>"+place.AddressDetails.Country.CountryNameCode;
                    html += "<br/><b>准确度：</b>"+place.AddressDetails.Accuracy;
                    html += "<br/><b>坐标：</b>"+place.Point.coordinates[1]+"   "+place.Point.coordinates[0];
                }
            }
            html += "</div>";
            return html;
        },
        async getBusinessInfo () {
            const { id } = this.$route.query
            const res = await getBusinessInfo({id})
            if (res.code === 1) {
                let { sortId, businessName, address, businessId, startTime, endTime, businessTop } = res.data.business
                this.addQuery = Object.assign({}, this.addQuery, res.data.business)
                this.tempQuery = res.data.business
                this.fileList.push({
                    url: businessTop,
                    name: businessName
                })
            }
        }
    },
    mounted () {
        this.$nextTick(async () => {
            await this.getBusinessInfo()
            this.initMap(this.addQuery.latitude, this.addQuery.longitude)
        })
    },
    created () {
        this.getHospitalList()
        
    }
} 
</script>

<style>

</style>
